package project_common

import (
	"github.com/gin-gonic/gin"
	"golang.org/x/net/context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func Run(r *gin.Engine, srvName, srvPort string) {
	srv := http.Server{
		Addr:    srvPort,
		Handler: r,
	}

	log.Printf("Server %s listen on %s port\n", srvName, srvPort)
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		log.Fatalf("Server %s listen on %s port: %v\n", srvName, srvPort, err)
	}

	quick := make(chan os.Signal)
	signal.Notify(quick, syscall.SIGINT, syscall.SIGTERM)
	<-quick

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	err := srv.Shutdown(ctx)
	if err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}
	select {
	case <-ctx.Done():
		log.Println("time out")
	}
	log.Println("Server exiting")
}
